package chances.epg.data.taglib;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.URLUtils;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.content.CategoryItem;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.context.AccessContextUtils;

/**
 * 编排列表. 支持分页查询.
 * 
 * @author Elysium
 *
 */
public class CategoryItemTag extends QueryListTag {
	private static final Logger logger = EpgLogFactory.getSystemLogger();
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = -1206180657029929973L;
	private String code;// 栏目编码
	private String itemtype;// 内容类型，为空时则查全部类型

	private int size = 10;// 条目数
	private String random = "false";// 是否随机
	private String isparent = "false";// 是否根据parent栏目查询编排
	private String title;// 内容名称
	private int hdType = 0;

	@Override
	public int doEndTag() throws JspException {
		String categoryCode = this.code;
		if (StringUtils.isBlank(categoryCode)) {
			categoryCode = this.getCurCategoryCode();
		}

		if (StringUtils.isBlank(categoryCode)) {
			return super.doEndTag();
		}

		try {
			// 随机获取指定数量的编排条目
			if ("true".equals(this.getRandom())) {
				this.queryRandomItem(categoryCode, isByParentCategory());
			} else if (StringUtils.isNotBlank(this.getPageName())) {
				this.queryItemByPage(categoryCode, isByParentCategory());
			} else {
				this.queryItemBySize(categoryCode, isByParentCategory());
			}
		} catch (Throwable ex) {
			logger.error("CategoryItemTag error", ex);
		}

		return super.doEndTag();
	}

	/**
	 * 按照指定数量随机获取.
	 */
	private void queryRandomItem(String categoryCode, boolean byParent) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("categoryCode", categoryCode);
		paramsMap.put("itemType", this.itemtype);
		paramsMap.put("title", this.title);
		if(this.hdType > 0) {
			paramsMap.put("hdType", this.hdType);
		}

		List<CategoryItem> result = this.getContentService().getCategoryItems(paramsMap, byParent);
		if (result.size() <= this.size) {
			this.setAttribute(this.getVar(), result);
		} else {
			List<CategoryItem> randomResult = new ArrayList<CategoryItem>();
			int[] randomSequence = this.getRandomSequence(result.size());
			for (int i = 0; i < this.size; i++) {
				randomResult.add(result.get(randomSequence[i]));
			}

			this.setCategoryItem(randomResult);
		}
	}

	/**
	 * 分页查询.
	 */
	private void queryItemByPage(String categoryCode, boolean byParent) {
		PageInfo pageInfo = this.createPageInfo(size);

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("categoryCode", categoryCode);
		paramsMap.put("itemType", this.itemtype);
		paramsMap.put("title", this.title);
		if(this.hdType > 0) {
			paramsMap.put("hdType", this.hdType);
		}

		List<CategoryItem> result = this.getContentService().getCategoryItems(paramsMap, this.start,
				pageInfo.getPageBean(), byParent);
		this.setPageInfo(pageInfo);
		this.setCategoryItem(result);
		this.pageNo = 0;
	}

	/**
	 * 查询指定数量的条目.
	 */
	private void queryItemBySize(String categoryCode, boolean byParent) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("categoryCode", categoryCode);
		paramsMap.put("itemType", this.itemtype);
		paramsMap.put("title", this.title);
		if(this.hdType > 0) {
			paramsMap.put("hdType", this.hdType);
		}

		List<CategoryItem> result = this.getContentService().getCategoryItems(paramsMap, this.start, this.size,
				byParent);
		this.setCategoryItem(result);
	}

	/**
	 * 
	 * @param result
	 */
	private void setCategoryItem(List<CategoryItem> result) {
		int index = 0;
		AccessContext context = AccessContextUtils.getAccessContext(pageContext);
		if (null != context) {
			for (CategoryItem categoryItem : result) {
				index++;
				String url = navigateUrlFactory.generateURL(context, categoryItem);
				url = URLUtils.appendParam(url, "pi", index + "");
				categoryItem.setUrl(url);
			}
		}
		this.setCollectionResult(result);
	}

	/**
	 * 生成随机序列.
	 * 
	 * @param total
	 * @return
	 */
	private int[] getRandomSequence(int total) {
		int[] sequence = new int[total];
		int[] output = new int[total];

		for (int i = 0; i < total; i++) {
			sequence[i] = i;
		}

		int end = total - 1;

		for (int i = 0; i < total; i++) {
			int num = RandomUtils.nextInt(end + 1);
			output[i] = sequence[num];
			sequence[num] = sequence[end];
			end--;
		}

		return output;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getItemtype() {
		return itemtype;
	}

	public void setItemtype(String itemtype) {
		this.itemtype = itemtype;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public String getRandom() {
		return random;
	}

	public void setRandom(String random) {
		this.random = random;
	}

	/**
	 * 是否根据父栏目.
	 * 
	 * @return
	 */
	public boolean isByParentCategory() {
		if ("true".equals(this.isparent)) {
			return true;
		} else {
			return false;
		}
	}

	public String getIsparent() {
		return isparent;
	}

	public void setIsparent(String isparent) {
		this.isparent = isparent;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getHdType() {
		return hdType;
	}

	public void setHdType(int hdType) {
		this.hdType = hdType;
	}
}
